import React, { memo } from "react";
import sty from "./sty.module.css";
import cs from "classnames";
import { PlayCircleOutlined } from "@ant-design/icons";
import { Link } from "react-router-dom";
import { message } from "antd";
import { useSelector, shallowEqual } from "react-redux";
import { getSizeImage } from "@/utils/format-utils";
import { reqSongDetail } from "@/api/song";
import {
  getSongDetail,
  changePlayListAndCount,
} from "@/pages/player/store/actionCreator";
import { useDispatch } from "react-redux";
const SongItem = (props) => {
  const { index, songName, singer, duration, coverPic, songId } = props;
  const dispatch = useDispatch();
  const { playList } = useSelector(
    (state) => ({
      playList: state.getIn(["player", "playList"]),
    }),
    shallowEqual
  );
  const playMusic = (e, isTo = false) => {
    if (!isTo) {
      e.preventDefault();
      dispatch(getSongDetail(songId));
      document.getElementById("audio").play();
    }
  };
  const addPlayList = (e, id) => {
    // 阻止超链接跳转
    e.preventDefault && e.preventDefault();
    const index = playList.findIndex((v) => v.id === id);
    switch (index) {
      case -1:
        reqSongDetail(id).then((res) => {
          if (res.code === 200) {
            let song = res.songs[0];
            playList.push(song);
            dispatch(changePlayListAndCount(playList));
            message.success({ content: "添加成功" });
          }
        });
        break;
      default:
        message.success({ content: "不能添加重复的歌曲" });
        break;
    }
  };

  return (
    <li className={sty.root}>
      <div className={cs("song-item", sty.index)}>{index}</div>
      {coverPic && (
        <img
          alt=""
          onClick={(e) => playMusic(e)}
          src={getSizeImage(coverPic, 50)}
          className="song-item"
        />
      )}
      <div className={cs(sty.info, coverPic && sty.hasImg)}>
        <PlayCircleOutlined
          onClick={(e) => playMusic(e)}
          className={sty.fontActive}
        />
        <Link className="txt1" to={`/song?id=${songId}`}>
          {songName}
        </Link>
      </div>
      <button
        onClick={(e) => addPlayList(e, songId)}
        className={cs("sprite_icon2", sty.btn)}
      ></button>
      <div className={sty.duration}>{duration}</div>
      <Link to={`/song?id=${songId}`}>{singer}</Link>
    </li>
  );
};
export default memo(SongItem);
